package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.pi.common.CodesConstants;
import com.pi.common.utils.TextUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.act.AllocationActionDto;
import com.pi.wms.entity.TwaDocSoDetails;
import com.pi.wms.entity.TwaDocSoHeader;
import com.pi.wms.entity.TwtActAllocationList;
import com.pi.wms.service.AllocationService;
import com.pi.wms.service.ParameterService;
import com.pi.wms.service.SoDetailsService;
import com.pi.wms.service.SoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/outbound/posodetails")
public class PoSoDetailsController extends BaseCrudController<TwaDocSoDetails, Long> {

	@Autowired
	private SoDetailsService service;
	@Autowired
	private SoService headerService;

	@Autowired
	private ParameterService parameterService;

    @Autowired
    private AllocationService allocateService;

	@Override
	protected ICrudService<TwaDocSoDetails, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "posodetails";
	}

	@Override
	protected TwaDocSoDetails newModel(HttpServletRequest request) {
		TwaDocSoDetails det=new TwaDocSoDetails();
		return det;
	}

	@Override
	protected void prepareDatatableConditions(Map<String, Object> query, DataTablesInput input) {
		Long userId = SecurityUtils.getLoginUserId();
		query.put("userId", userId.toString());
		super.prepareDatatableConditions(query, input);
	}
	

	@Override
	@GetMapping(value = { "", "/{headerId}" })
	public String list(Model model, @PathVariable Map<?, ?> params, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		TwaDocSoHeader header = this.getHeader(params);
		model.addAttribute("r", header);
		if (header!=null){
			Map<String,Object> maps=new HashMap<String,Object>();
			maps.put("m.headerId", header.getId());
			model.mergeAttributes(maps);
		}
		return super.list(model, params, request, redirectAttributes);
	}
	
    @Override
	@GetMapping(value = { "add" })
    public String add(Model model, HttpServletRequest request) {
    	TwaDocSoHeader header =this.getHeader(request);
		model.addAttribute("r", header);
		String flag=null;
		if (header!=null){
			model.addAttribute("headerId", header.getId());
            //
            flag=this.parameterService.stringValue(WmsConstants.PARAM_DOC_EDIT_ON_CREATE_SO);
            if  ((CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(flag))
                    && (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))){
                this.addWarnMessage(model, new String[]{"单证已经开始作业，不能修改!"});
                return this.redirect("/"+String.valueOf(header.getId()));
            }
		}
        return super.add(model, request);
    }
    
    @Override
    @GetMapping(value = { "edit/{id}" })
    public String edit(@ModelAttribute("m") TwaDocSoDetails m, Model model, HttpServletRequest request,
                       RedirectAttributes redirectAttributes) {
    	TwaDocSoHeader header =this.getHeader(request);
        model.addAttribute("r", header);
        String flag=null;
		if (header!=null){
			model.addAttribute("headerId", header.getId());
            //
            flag=this.parameterService.stringValue(WmsConstants.PARAM_DOC_EDIT_ON_CREATE_SO);
            if  ((CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(flag))
                    && (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))){
                this.addWarnMessage(redirectAttributes, new String[]{"单证已经开始作业，不能修改!"});
                return this.redirect("/"+String.valueOf(header.getId()));
            }
		}
        return super.edit(m, model, request, redirectAttributes);
    }
    
	@Override
	public String save(Model model, TwaDocSoDetails m, BindingResult result, HttpServletRequest request,
                       RedirectAttributes redirectAttributes) {

		Object headerId = getParamValue(request, "headerId");
		TwaDocSoHeader header =this.getHeader(request);
        model.addAttribute("r", header);
        
        m.setHeaderId(header.getId());
        
        boolean isNew = false;
        if (null == m.getId()) {
            isNew = true;
        }
        String appendUrl = super.save(model, m, result, request, redirectAttributes);
        if (isNew) {
            //service.save(m);
        }
		if (StringUtils.startsWith(appendUrl, "redirect:")) {
			if (headerId != null) {
				appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
			}
		}
		return appendUrl;
	}

    @GetMapping("check/linenumber")
    @ResponseBody
    public boolean checkLinenumber(@RequestParam("lineNumber") String linenumber,
            @RequestParam("oldLinenumber") String oldLinenumber, @RequestParam("headerId") Long headerId) {
        if (null != oldLinenumber && oldLinenumber.equals(linenumber == null ? null : linenumber.toString())) {
            return true;
        }
        return service.countByLineNumberAndHeaderId(linenumber, headerId) <= 0;
    }

    @GetMapping("check/material")
    @ResponseBody
    public boolean checkPart(@RequestParam("material") Long materialId, @RequestParam("oldMaterial") String oldMaterialId,
            @RequestParam("headerId") Long headerId) {
        if (null != oldMaterialId && oldMaterialId.equals(materialId == null ? null : materialId.toString())) {
            return true;
        }
        return service.countByMaterialIdAndHeaderId(materialId, headerId) <= 0;
    }



	@PostMapping("allocate")
	public String allocate(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
						   RedirectAttributes redirectAttributes) {
		Object headerId = getParamValue(request, "headerId");
		String appendUrl = super.redirect("");
		if ((StringUtils.startsWith(appendUrl, "redirect:")) && (headerId != null) && (!StringUtils.isNullOrBlank(headerId.toString()))) {
			appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
		}
		model.addAttribute("params", getParams(request));
		String msg="";
		boolean failed=false;
		if ((ids == null) || (ids.length==0)){
			addErrorMessage(redirectAttributes, "请选中需要分配的订单行");
			return appendUrl;
		}
		TwaDocSoHeader header=null;
		TwaDocSoDetails details=null;
		AllocationActionDto actionDto=null;
		String batchnum = TextUtils.genBatchNumber();
		List<TwtActAllocationList> allocations=null;
		try {
			actionDto=new AllocationActionDto();
			for (Long id : ids) {
				if (id==null){
					continue;
				}
				details=this.service.findById(id);
				if (details==null){
					addErrorMessage(redirectAttributes, "找不到订单行,请确认是否已删除.ID:"+String.valueOf(id));
					return appendUrl;
				}
				if (WmsConstants.SO_STATUS_SHIP.compareTo(details.getLineStatus())<=0){
					continue;
				}
				if (header==null){
					header=this.headerService.findById(details.getHeaderId());
					if (header==null){
						addErrorMessage(redirectAttributes, "找不到订单,请确认是否已删除.ID:"+String.valueOf(details.getHeaderId()));
						return appendUrl;
					}
					if (WmsConstants.SO_STATUS_SHIP.compareTo(header.getStatus())<=0){
						addErrorMessage(redirectAttributes, "订单已经完全发货,不能再分配.单号:"+header.getDocumentNumber());
						return appendUrl;
					}
				}
				this.fill(header, actionDto);
				allocations = this.allocateService.allocate(batchnum, header.getDocumentNumber(), details.getLineNumber(), actionDto);
				if ((allocations==null)||(allocations.size()==0)) {
					failed=true;
					if ((actionDto!=null) && (!StringUtils.isNullOrBlank(actionDto.getErrorText()))){
						msg=actionDto.getErrorText();
					}
					addErrorMessage(redirectAttributes, "分配失败:"+msg);
					break;
				}
			}
			if (!failed){
				addSuccessMessage(redirectAttributes, "分配订单数据成功");
			}
		} catch (Exception e) {
			addErrorMessage(redirectAttributes, "分配订单失败"+e.getMessage());
		}
		return appendUrl;
	}

	@PostMapping("del/{id}")
	@Override
	public String del(@PathVariable("id") Long id, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        Object headerId = getParamValue(request, "headerId");
    	String appendUrl = super.redirect("");
        if ((StringUtils.startsWith(appendUrl, "redirect:")) && (headerId != null) && (!StringUtils.isNullOrBlank(headerId.toString()))) {
            appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
        }
		model.addAttribute("params", getParams(request));
		String msg="";
		if (id!=null) {
			msg=this.delete(id);
			if (StringUtils.isNullOrBlank(msg)){
				addSuccessMessage(redirectAttributes, "删除数据成功");
			}else{
				addErrorMessage(redirectAttributes, "删除数据失败:"+msg);
			}
		}
		return appendUrl;
	}
	
    @Override
    public String del(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        Object headerId = getParamValue(request, "headerId");
    	String appendUrl = super.redirect("");
        if ((StringUtils.startsWith(appendUrl, "redirect:")) && (headerId != null) && (!StringUtils.isNullOrBlank(headerId.toString()))) {
            appendUrl += (appendUrl.endsWith("/") ? headerId : "/" + headerId);
        }
		model.addAttribute("params", getParams(request));
		String msg="";
		if (ids != null && ids.length > 0) {
			try {
				for (Long id : ids) {
					msg=this.delete(id);
					if (!StringUtils.isNullOrBlank(msg)){
						addErrorMessage(redirectAttributes, "删除数据失败:"+msg);
						return appendUrl;
					}
				}
				addSuccessMessage(redirectAttributes, "删除数据成功");
			} catch (Exception e) {
				addErrorMessage(redirectAttributes, "删除数据失败");
			}
		}
		return appendUrl;
    }
    
    private String delete(Long id){
    	String msg="";
    	if (id==null){
    		return msg;
    	}
        String flag=null;
        TwaDocSoHeader header=null;
    	try{
    		TwaDocSoDetails details=this.getCrudService().findById(id);
    		if (details==null){
    			msg="找不到订单明细,请确认是否已删除.单证行ID="+String.valueOf(id);
    			return msg;
    		}
    		if (!WmsConstants.SO_STATUS_CREATE.equals(details.getLineStatus())){
    			msg="单证明细非创建状态,不能删除.当前状态:"+details.getLineStatus();
    			return msg;
    		}
    		if ((details.getQtyAllocatedEach()!=null) && (details.getQtyAllocatedEach().compareTo(BigDecimal.ZERO)>0)){
    			msg="单证明细已经分配,不能删除.分配数量:"+String.valueOf(details.getQtyAllocatedEach());
    			return msg;
    		}
            //
            flag=this.parameterService.stringValue(WmsConstants.PARAM_DOC_EDIT_ON_CREATE_SO);
            if  (CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(flag)) {
                header=this.getHeader(details.getHeaderId());
                if ((header!=null)&& (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))){
                    msg = "单证已经开始作业，不能修改!";
                    return msg;
                }
            }
    		this.getCrudService().delete(details);
    	}catch(Exception e){
    		msg="删除订单明细异常:"+e.getMessage();
    	}
    	return msg;
    }

	private void fill(TwaDocSoHeader document, AllocationActionDto actionDto){
		if ((document==null)||(actionDto==null)){
			return;
		}
		actionDto.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
		actionDto.setPackAllocateMode(CodesConstants.COMMON_FLAG_NO);
		actionDto.setWorker(SecurityUtils.getLoginUsername());
	}

    private TwaDocSoHeader getHeader(HttpServletRequest request){
		Object headerId = getParams(request).get("headerId");
		return this.getHeader(headerId);
    }

    private TwaDocSoHeader getHeader(Map<?,?> params){
		Object headerId = params.get("headerId");
		return this.getHeader(headerId);
    }
    
    private TwaDocSoHeader getHeader(Object headerId){
    	TwaDocSoHeader header = new TwaDocSoHeader();
		if (null != headerId && StringUtils.isNotBlank(headerId.toString())) {
			header = headerService.getById(Long.valueOf(headerId.toString()));
		}
		return header;
    }
	
}
